/**
 * jqgrid 分页信息
 */
var rowNum = 20;//默认每页20条记录
var rowList = [10, 20, 30, 50];//每页记录数可选项
var jsonReader = {
    root: 'list', //Json数据
    page: 'pageNum', //当前页
    total: 'pages', //总页数
    records: 'total', //总记录数
    repeatitems: false // 如果设为false,则jqGrid在解析json时, 会根据name来搜索对应的数据元素(即可以json中元素可以不按顺序), 而所使用的name是来自于colModel中的name设定.
};

/**
 * 内容区域Dom
 */
var pageContentArea = $('.page-content-area');

/**
 * 全局ajax控制, 异常处理
 */
$(document).ajaxError(function (e, xhr, opt) {
    $('.modal-backdrop.fade.in').removeClass('in');
    pageContentArea.html(xhr.responseText).css("overflow","auto");
});

/**
 * 全局ajax控制, session 失效处理
 */
$.ajaxSetup({
    contentType: "application/x-www-form-urlencoded;charset=utf-8",
    complete: function (XMLHttpRequest, textStatus) {
        //通过XMLHttpRequest取得响应头，sessionstatus，
        var sessionstatus = XMLHttpRequest.getResponseHeader("sessionstatus");
        if (sessionstatus == "timeout") {
            //如果超时就处理 ，指定要跳转的页面
            window.location.replace(ctx + "/login");
        }
    }
});

function HashMap() {
    //定义长度
    var length = 0;
    //创建一个对象
    var obj = new Object();

    /**
     * 判断Map是否为空
     */
    this.isEmpty = function () {
        return length == 0;
    };

    /**
     * 判断对象中是否包含给定Key
     */
    this.containsKey = function (key) {
        return (key in obj);
    };

    /**
     * 判断对象中是否包含给定的Value
     */
    this.containsValue = function (value) {
        for (var key in obj) {
            if (obj[key] == value) {
                return true;
            }
        }
        return false;
    };

    /**
     *向map中添加数据
     */
    this.put = function (key, value) {
        if (!this.containsKey(key)) {
            length++;
        }
        obj[key] = value;
    };

    /**
     * 根据给定的Key获得Value
     */
    this.get = function (key) {
        return this.containsKey(key) ? obj[key] : null;
    };

    /**
     * 根据给定的Key删除一个值
     */
    this.remove = function (key) {
        if (this.containsKey(key) && (delete obj[key])) {
            length--;
        }
    };

    /**
     * 获得Map中的所有Value
     */
    this.values = function () {
        var _values = new Array();
        for (var key in obj) {
            _values.push(obj[key]);
        }
        return _values;
    };

    /**
     * 获得Map中的所有Key
     */
    this.keySet = function () {
        var _keys = new Array();
        for (var key in obj) {
            _keys.push(key);
        }
        return _keys;
    };

    /**
     * 获得Map的长度
     */
    this.size = function () {
        return length;
    };

    /**
     * 清空Map
     */
    this.clear = function () {
        length = 0;
        obj = new Object();
    };
}

/**
 * 为Object增加keys方法
 */
Object.keys = function (obj) {
    var keys = [];
    for (var pro in obj) {
        keys.push(pro);
    }
    return keys;
};

/**
 * 为Object增加values方法
 */
Object.values = function (obj) {
    var values = [];
    for (var pro in obj) {
        values.push(obj[pro]);
    }
    return values;
};

$(function () {
    $.extend({
        aop: function (target, before, after) {
            return $.extend(function () {
                var result;
                if ($.isFunction(before)) {
                    before.apply(this, arguments);
                }
                if ($.isFunction(target)) {
                    result = target.apply(this, arguments);
                }
                if ($.isFunction(after)) {
                    after.apply(this, arguments);
                }
                return result;
            }, target);
        }
    });
    $.fn.extend({
        //表单加载json对象数据
        setForm: function (jsonValue) {
            var obj = this;
            $.each(jsonValue, function (name, ival) {
                var $oinput = obj.find('[name=' + name + ']');
                if ($oinput) {
                    if ($oinput.length == 1) {
                        if ($oinput.prop("tagName").toLocaleLowerCase() == 'input') {
                            if ($oinput.attr('type') == 'checkbox') {
                                if (ival !== null) {
                                    $oinput.attr('checked', 'checked');
                                }
                            } else {
                                obj.find('[name=' + name + ']').val(ival);
                            }
                        } else if ($oinput.prop("tagName").toLocaleLowerCase() == 'textarea') {
                            obj.find('[name=' + name + ']').text(ival);
                            obj.find('[name=' + name + ']').val(ival);
                        } else if ($oinput.prop("tagName").toLocaleLowerCase() == 'select') {
                            //$oinput.find("option[value=" + ival + "]").attr("selected", true).trigger("chosen:updated");
                            $oinput.val(ival).trigger("chosen:updated");
                        }
                    } else if ($oinput.length > 1) {
                        if ($oinput.attr('type') == 'checkbox') {
                            if (ival !== null) {
                                var checkArray = ival.split(',');
                                for (var i = 0; i < $oinput.length; i++) {
                                    for (var j = 0; j < checkArray.length; j++) {
                                        if ($oinput[i].value == checkArray[j]) {
                                            $oinput[i].attr('checked', 'checked');
                                        }
                                    }
                                }
                            }
                        } else if ($oinput.attr('type') == 'radio') {
                            for (var i = 0; i < $oinput.length; i++) {
                                if ($oinput[i].value == ival) {
                                    //$($oinput[i]).attr('checked', 'checked');
                                    $($oinput[i]).click();
                                    break;
                                }
                            }
                        }
                    }
                }
            });
        }
    });

    $.fn.formReset = function () {
        this.find(':input:not(:button):not(:checkbox):not(:radio)').each(function () {
            $(this).val('');
        });
        this.find('input[type=checkbox], input[type=radio]').each(function () {
            $(this).removeAttr('checked');
        });
        this.find('select').each(function(){
            $(this).val('').trigger('chosen:updated');
        });
        return this;
    };

    $.launchDialog = function (id) {
        function launchModalWin(id) {
            $('#' + id).modal({
                backdrop: 'static',
                keyboard: false,
                show: true
            });
        }

        return launchModalWin(id);
    };

    $.alertMessage = function (msg, $posObj) {
        var $msgObj = $('<div id="errorMessage" class="alert alert-danger alert-dismissable">\
                            <button type="button" class="close" data-hidden="alert" data-dismiss="alert" aria-hidden="true">&times;</button>\
                            ' + msg + '\
                        </div>');
        setTimeout(function () {
            $msgObj.hide(500, function () {
                $(this).remove();
            });
        }, 2000);
        return $posObj.prepend($msgObj);
    };

    $.successMessage = function (msg, $posObj) {
        var $msgObj = $('<div id="successMessage" class="alert alert-success alert-dismissable">\
                            <button type="button" class="close" data-hidden="alert" data-dismiss="alert" aria-hidden="true">&times;</button>\
                            ' + msg + '\
                        </div>');
        setTimeout(function () {
            $msgObj.hide(500, function () {
                $(this).remove();
            });
        }, 2000);
        return $posObj.prepend($msgObj);
    };

    $.bindSwitch = function () {
        var $bindObj = $('.ace-switch').on('click', function () {
            $(this).val() === 'off' ? $(this).val('on') : $(this).val('off');
        }).val('off').trigger('click');
        return $bindObj;
    };

    $.fn.dynamicPop = function (content, destory, width, placement) {
        try {
            // 如果存在popover，将其先destory
            this.popover('destroy');
        } catch (x) {
            // 不需要做处理，主要是捕获如果没有popover抛出的异常
        }
        width = !width ? '150px' : (width + 'px');
        var $dynamicPop = this.popover({
            html: true,
            content: '<div style="width:' + width + '">' + content + '</div>',
            placement: !placement ? 'right' : placement,
            delay: {show: 500, hide: 100}
        }).popover('show');
        if (!destory || destory === -1) {
            destory = 2000;
        }
        setTimeout(function () {
            $dynamicPop.popover('destroy')
        }, destory);
    };

    $.fn.confirm = function (msg, success, failed) {
        if (!msg) {
            msg = '';
        }
        var $confirmContent = '<div id="dialog-confirm" class="show">\
                                   ' + msg + '\
                               </div>';
        $(this).append($confirmContent);

        $('#dialog-confirm').dialog({
            resizable: false,
            modal: true,
            //title: '<div class="widget-header"><h4 class="smaller"><i class="ace-icon fa fa-exclamation-triangle red"></i>确认框</h4></div>',
            title_html: true,
            buttons: [
                {
                    html: '<i class="ace-icon fa fa-check-square-o bigger-110"></i>&nbsp;确认',
                    'class': 'btn btn-success btn-minier',
                    click: function () {
                        $(this).dialog('close');
                        $(this).remove();
                        if ($.isFunction(success)) {
                            success();
                        }
                    }
                }, {
                    html: '<i class="ace-icon fa fa-times bigger-110"></i>&nbsp; 取消',
                    'class': 'btn btn-minier',
                    click: function () {
                        $(this).dialog('close');
                        $(this).remove();
                        if ($.isFunction(failed)) {
                            this.call(failed, null);
                        }
                    }
                }
            ]
        });
    };

    $.fn.extend({
        serializeObject: function () {
            var o = {};
            var a = this.serializeArray();
            $.each(a, function () {
                if (o[this.name]) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        }
    });
});

/**
 * 下载文件
 *
 * @param path
 */
function downloadFile(path) {
    var expForm = $('#expForm');
    if (expForm.length > 0) {
        $(expForm).find("[name='filePath']").val(path);
        expForm.submit();// 表单提交
    } else {
        var form = $('<form>');// 定义一个form表单
        form.attr('id', 'expForm');
        form.attr('style', 'display:none');
        form.attr('target', '');
        form.attr('method', 'post');
        form.attr('action', ctx + '/file/download');
        var input = $('<input>');
        input.attr('type', 'hidden');
        input.attr('name', 'filePath');
        input.attr('value', path);
        $('body').append(form);// 将表单放置在web中
        form.append(input);
        form.submit();// 表单提交
    }
}

function isNotEmpty(obj){
    if (obj != null && obj != '' && obj != undefined){
        return true;
    }
    return false;
}

/**
 * 转换属性名大小写
 *
 * @param columnName
 * @returns {string}
 */
function getPropertyName(columnName) {
    var result = '';
    var bs = columnName.split("_");
    for (var i = 0; i < bs.length; i++) {
        if (i == 0) {
            result += bs[i].toLowerCase();
        } else {
            var c = bs[i].split("");
            for (var j = 0; j < c.length; j++) {
                if (j == 0) {
                    if (c[j] >= 'A' && c[j] <= 'Z') {
                        result += c[j];
                    } else if (c[j] >= 'a' && c[j] <= 'z') {
                        result += String.fromCharCode(c[j].charCodeAt() - 32);
                    } else {
                        result += c[j];
                    }
                } else {
                    if (c[j] >= 'A' && c[j] <= 'Z') {
                        result += String.fromCharCode(c[j].charCodeAt() + 32);
                    } else if (c[j] >= 'a' && c[j] <= 'z') {
                        result += c[j];
                    } else {
                        result += c[j];
                    }
                }
            }
        }
    }
    return result;
}